import React, { useEffect,useState,useRef } from 'react'
import { Card,Form,Button,Input,Cascader, message } from 'antd';
import { ArrowLeftOutlined,LoadingOutlined } from '@ant-design/icons';
import PictureWall from '../components/PictureWall'
import RichTextEditor from '../components/RichTextEditor'
import { connect } from 'react-redux';

import { reqCategories,reqAddProduct,reqModifyProduct } from '../../../api';
import './AddAndModifyProduct.css'

const { Item } = Form

export default connect(state=>({categories:state.categories}))(function AddAndModifyProduct(props) {
  console.log(props)
  let {type,_id,name,desc,price,category,imgs:_imgs,detail}=props.location.state
  const [options,setOptions] =useState([])
  const [categoryInfo,setCategoryInfo] =useState(null)
  const editor =useRef()
  const pictureWall =useRef()

  const title=(<span style={{fontSize:'20px',font:'bold 24px 宋体'}}> <Button type='link' onClick={()=>props.history.go(-1)}><ArrowLeftOutlined style={{color:'#5fceb8',fontSize:'20px'}}/></Button> 添加商品</span>)

    useEffect(()=>{
    async function getData(){
      let list= props.categories.length!==0?props.categories:await reqCategories()  
      setOptions(list.reduce((pre,cur)=>{//不显示没有第三级分类的类别，1.一级类别children为空 2.二级类别children为空 
        if(cur.children.length!==0){
          cur.children.forEach((i,index)=>{
            if(i.children.length===0){
              cur.children.splice(index,1)
            }
          })
          if(cur.children.length!==0){
            pre.push(cur)
          }
        }
        return pre
      },[]))
    }
    if(options.length===0)getData()
  },[options,props])

  const displayRender=(label)=>{
    return label.join(' >> ')
  }

  const cascaderChange=(value, selectedOptions)=>{
    if(value.length===0)return
    let grandPa=selectedOptions.find(i=>i._id===selectedOptions[0]._id)
    let parent_index=grandPa.children.findIndex(i=>i.id===selectedOptions[1].id)
    let parent=grandPa.children[parent_index]
    let child_index=parent.children.findIndex(i=>i.id===selectedOptions[selectedOptions.length-1].id)
    let categories=[grandPa.name,parent.name,parent.children[child_index].name]
    let obj={name:selectedOptions[selectedOptions.length-1].name,id:selectedOptions[0]._id,parent_index,child_index,categories}
    setCategoryInfo(obj)
  }

  const onFinish=(values)=>{
    values.imgs=JSON.stringify(pictureWall.current.state.fileList.map(i=>i.response?i.response.file.path:i.thumbUrl))
    values.detail=editor.current.getDetail()
    values.category=JSON.stringify(categoryInfo?categoryInfo:category)
    let keys=Object.keys(values)
    let params= keys.reduce((pre,cur)=>{
      pre.append(cur,values[cur])
      return pre
    },new FormData())
    console.log(values)
    if(type==='modify'){
      params.append('id',_id)
      reqModifyProduct(params).then(res=>{
        message.success(res.msg)
        props.history.go(-1)
      }).catch(err=>message.error(err.message))
    }else{
      reqAddProduct(params).then(res=>{
        message.success(res.msg)
        props.history.go(-1)
      }).catch(err=>{
        message.error(err.message)
      })
    }
    
  }

  const setImgs=(newImgs)=>{
    _imgs=newImgs
    console.log(_imgs)
  }

  return (
    <Card title={title}> 
      <Form
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 10 }}
        onFinish={onFinish}
        initialValues={type==='modify'?{name,desc,price,category:category.categories}:null}
      >
        <Item label='商品名称：' name='name' rules={[{required:true,message:'必填'}]}>
          <Input  placeholder="请输入商品名称" />
        </Item>
        <Item label='商品描述：' name='desc' rules={[{required:true,message:'必填'}]}>
          <Input.TextArea autoSize={{ minRows: 1, maxRows: 6 }} placeholder="请输入商品描述"/>
        </Item>
        <Item label='商品价格：' name='price' rules={[{required:true,message:'必填'}]}>
          <Input placeholder="请输入商品价格" addonBefore="￥" addonAfter="元"/>
        </Item>
        <Item label='商品分类：' name='category' rules={[{required:true,message:'必填'}]}>
          <Cascader displayRender={displayRender} notFoundContent={<><LoadingOutlined />正在加载...</>} onChange={cascaderChange} options={options} fieldNames={{ label:'name',value:'name',children:'children'}} placeholder='请选择商品分类'></Cascader>
        </Item>
        <Item label='商品图片：' name='imgs'>
          <PictureWall {...{type,_imgs,_id,setImgs}} ref={pictureWall}></PictureWall>
        </Item>
        <Item label='商品详情：' name='detail' wrapperCol={{span:20}}>
          <RichTextEditor ref={editor} detail={detail}></RichTextEditor>
        </Item>
        <Item labelCol={{span:4,offset:4}}>
          <Button type='primary' htmlType='submit'>提交</Button>
        </Item>
      </Form>
    </Card>
  )
})
